#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/2/13
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R35_EC_PaidCreditInformationSummaryCntCheck
# @Software  :PyCharm

'''eof
name:申请企业已结清信贷业务为资产处置、被剥离负债、欠息汇总、垫款汇总、担保代偿或第三方代偿笔数校验
code:R35_EC_PaidCreditInformationSummaryCntCheck
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''



import sys


reload(sys)
sys.setdefaultencoding('utf-8')


null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = EC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None


def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def paidCreditInformationSummaryCntCheck():
    """
    Factor1=max(已结清信贷信息概要(资产处置、被剥离负债、欠息汇总)（ECRSummarySettled01）中"由资产管理公司处置的债务（笔数）"，
    已结清由资产管理公司处置的债务（ECRPaidAssetDisp）中统计"信用报告编号"的数量）；
    Factor2=已结清信贷信息概要(资产处置、被剥离负债、欠息汇总)（ECRSummarySettled01）中"被剥离负债汇总（笔数）"（被剥离无明细）；
    # 删除Factor3
    Factor3=max(已结清信贷信息概要(资产处置、被剥离负债、欠息汇总)（ECRSummarySettled01）中"欠息汇总（笔数）"，
    已结清欠息（ECRPaidDebtInterest）中统计"信用报告编号"的数量）；

    Factor4=max(已结清信贷信息概要(垫款汇总、代偿)（ECRSummarySettled04）中的"垫款汇总（笔数）"，
    已结清垫款（ECRPaidPaidback）中统计"信用报告编号"的数量）；
    Factor5=max(已结清信贷信息概要(垫款汇总、代偿)（ECRSummarySettled04）中的"担保代偿或第三方代偿的债务（笔数）"，
    已结清担保代偿信息（ECRPaidGuarantee）中统计"信用报告编号"的数量；
    Factor=sum Factor{1~5}。

    Factor6=已结清担保代偿信息概要（ECRSummarySettled03）中的"由担保公司代偿的债务笔数" + "由保险公司代偿的债务笔数"（待解决）
    :return:
    """
    # 新增Factor6
    ECRSummarySettled01 = getTable('ECRSummarySettled01')
    ECRPaidAssetDisp = getTable('ECRPaidAssetDisp')
    # ECRPaidDebtInterest = getTable('ECRPaidDebtInterest')
    ECRSummarySettled04 = getTable('ECRSummarySettled04')
    ECRPaidPaidback = getTable('ECRPaidPaidback')
    ECRPaidGuarantee = getTable('ECRPaidGuarantee')
    ECRSummarySettled03 = getTable('ECRSummarySettled03')

    if ECRSummarySettled01 is None and ECRPaidAssetDisp is None  \
        and ECRSummarySettled04 is None and ECRPaidPaidback is None and ECRPaidGuarantee is None:
        return u'缺失值'
    else:
        # Factor1
        if ECRSummarySettled01 is None:
            result1 = None
        elif ECRSummarySettled01 == [{}]:
            result1 = 0
        else:
            Debtsdamf_Number = ECRSummarySettled01[0].get('Debtsdamf_Number')
            if isfloat(Debtsdamf_Number):
                result1 = float(Debtsdamf_Number)
            else:
                result1 = None
        if ECRPaidAssetDisp is None:
            result2 = None
        elif ECRPaidAssetDisp == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRPaidAssetDisp:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x:x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor1 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor1 = max(result1, result2)

        # Factor2
        if ECRSummarySettled01 is None:
            Factor2 = None
        elif ECRSummarySettled01 == [{}]:
            Factor2 = 0
        else:
            StrippedLiabilitie_Number = ECRSummarySettled01[0].get('StrippedLiabilitie_Number')
            if isfloat(StrippedLiabilitie_Number):
                Factor2 = float(StrippedLiabilitie_Number)
            else:
                Factor2 = None

        # Factor3  删除 已结清欠息汇总的计数




        # Factor4
        if ECRSummarySettled04 is None:
            result1 = None
        elif ECRSummarySettled04 == [{}]:
            result1 = 0
        else:
            PaidbackBalancesum_Number = ECRSummarySettled04[0].get('PaidbackBalancesum_Number')
            if isfloat(PaidbackBalancesum_Number):
                result1 = float(PaidbackBalancesum_Number)
            else:
                result1 = None
        if ECRPaidPaidback is None:
            result2 = None
        elif ECRPaidPaidback == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRPaidPaidback:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x: x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor4 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor4 = max(result1, result2)

        # Factor5
        if ECRSummarySettled04 is None:
            result1 = None
        elif ECRSummarySettled04 == [{}]:
            result1 = 0
        else:
            Guarantee_Number = ECRSummarySettled04[0].get('Guarantee_Number')
            if isfloat(Guarantee_Number):
                result1 = float(Guarantee_Number)
            else:
                result1 = None

        if ECRPaidGuarantee is None:
            result2 = None
        elif ECRPaidGuarantee == [{}]:
            result2 = 0
        else:
            flag = []
            for i in ECRPaidGuarantee:
                reportNo = i.get('ReportNo')
                if reportNo in null_type_list:
                    flag.append(None)
                else:
                    flag.append(1)
            flag = filter(lambda x: x is not None, flag)
            if len(flag) == 0:
                result2 = None
            else:
                result2 = sum(flag)
        if result1 is None and result2 is None:
            Factor5 = None
        else:
            if result1 is None:
                result1 = 0
            if result2 is None:
                result2 = 0
            Factor5 = max(result1, result2)

        # 新增Factor6
        if ECRSummarySettled03 is None:
            Factor6 = None
        elif ECRSummarySettled03 == [{}]:
            Factor6 = 0
        else:
            GuaranteeNum = ECRSummarySettled03[0].get('GuaranteeNum')
            InsuranceNum = ECRSummarySettled03[0].get('InsuranceNum')
            if isfloat(GuaranteeNum) is None and isfloat(InsuranceNum) is None:
                Factor6 = None
            else:
                if isfloat(GuaranteeNum) is None:
                    GuaranteeNum = 0
                if isfloat(InsuranceNum) is None:
                    InsuranceNum = 0
                Factor6 = GuaranteeNum + InsuranceNum

        if Factor1 is None and Factor2 is None  and Factor4 is None and Factor5 is None \
                and Factor6 is None:
            return u'缺失值'
        else:
            if Factor1 is None:
                Factor1 = 0
            if Factor2 is None:
                Factor2 = 0

            if Factor4 is None:
                Factor4 = 0
            if Factor5 is None:
                Factor5 = 0
            if Factor6 is None:
                Factor6 = 0

            Factor = Factor1 + Factor2  + Factor4 + Factor5 + Factor6
            return round(Factor, 4)


result = paidCreditInformationSummaryCntCheck()

# if __name__ == '__main__':
#     file_obj = open(r'F:/testgit/changjiang_qianyi/EG/EC_DSJ.json', 'r')
#     content = file_obj.read()
#     EC_DSJ = json.loads(content, strict=False)['EC_DSJ']
#     aa = paidCreditInformationSummaryCntCheck()
#     print aa